package org.dromara.job.snailjob;

import com.aizuda.snailjob.client.job.core.annotation.JobExecutor;
import com.aizuda.snailjob.client.job.core.dto.JobArgs;
import com.aizuda.snailjob.client.model.ExecuteResult;
import com.aizuda.snailjob.common.core.util.JsonUtil;
import com.aizuda.snailjob.common.log.SnailJobLog;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.time.DateFormatUtils;
import org.dromara.exam.domain.bo.ExamProjectBo;
import org.dromara.exam.domain.vo.ExamProjectVo;
import org.dromara.exam.service.IExamAnswerService;
import org.dromara.exam.service.IExamProjectService;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;


/**
 * @author xiyin321
 */
@Component
@JobExecutor(name = "submitProjectJobExecutor")
@RequiredArgsConstructor
public class SubmitProjectJobExecutor {
    private final IExamProjectService examProjectService;

    public ExecuteResult jobExecute(JobArgs jobArgs) {
        // 1. 查询所有进行中的项目
        ExamProjectBo bo = new ExamProjectBo();
        bo.setStatus("1");
        List<ExamProjectVo> projects = examProjectService.queryList(bo);

        // 2. 过滤并处理过期项目
        projects.stream()
            .filter(this::hasValidEndTime)
            .filter(project -> isTimeExpired(project.getSetting().getExamSetting().getEndTime()))
            .forEach(project -> {
                try {
                    examProjectService.cancelPublishProject(project.getId());
//                    SnailJobLog.LOCAL.info("submitProjectJobExecutor. jobArgs:{}", JsonUtil.toJsonString(jobArgs));
//                    SnailJobLog.REMOTE.info("submitProjectJobExecutor. jobArgs:{}", JsonUtil.toJsonString(jobArgs));
                    SnailJobLog.LOCAL.info("项目自动停止成功 ID：{} | 结束时间：{}",
                        project.getId(),
                        DateFormatUtils.format(project.getSetting().getExamSetting().getEndTime(), "yyyy-MM-dd HH:mm:ss"));
                } catch (Exception e) {
//                    SnailJobLog.LOCAL.info("submitProjectJobExecutor. jobArgs:{}", JsonUtil.toJsonString(jobArgs));
//                    SnailJobLog.REMOTE.info("submitProjectJobExecutor. jobArgs:{}", JsonUtil.toJsonString(jobArgs));
                    SnailJobLog.LOCAL.error("项目停止异常 ID：{}", project.getId(), e);
                }
            });

        return ExecuteResult.success();
    }

    // 辅助方法：验证项目是否包含有效结束时间
    private boolean hasValidEndTime(ExamProjectVo project) {
        return project.getSetting() != null
            && project.getSetting().getExamSetting() != null
            && project.getSetting().getExamSetting().getEndTime() != null;
    }

    // 时间过期判断（包含时区安全处理）
    private boolean isTimeExpired(Date targetDate) {
        if (targetDate == null) {
            return false;
        }

        // 使用系统默认时区（确保与数据库存储时区一致）
        ZoneId zone = ZoneId.systemDefault();
        Instant now = Instant.now();
        Instant target = targetDate.toInstant();
        return now.isAfter(target);
    }
}
